package controller;


import pojoCla.NewsChnl;
import pojoCla.SysUser;
import pojoCla.UserMsg;
import util.ChnlUtil;
import util.UserUtil;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.xml.ws.spi.http.HttpContext;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;

@WebServlet("/doUser")
public class DoUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");
        if(!method.equals("checkLogin") && !method.equals("doExit")){
            SysUser user = (SysUser) request.getSession().getAttribute("user");
            if("1".equals(user.getSysCode())){
                response.sendRedirect("error.jsp");
                return;
            }
        }
        UserUtil uu = new UserUtil();
        Method dm = null;
        try {
            dm = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class,UserUtil.class);
            dm.invoke(this,request,response,uu);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private void checkLogin(HttpServletRequest request,HttpServletResponse response,UserUtil uu)throws ServletException, IOException{
        ChnlUtil cu = new ChnlUtil();
        HttpSession session = request.getSession();

        String vcode =(String)session.getAttribute("vcode");
        String captcha = request.getParameter("Captcha");
        if(vcode.equals(captcha)){ //先检验验证码
            //检查是否有匹配数据
            //获取用户名和密码
            String username = request.getParameter("username");
            SysUser user = uu.cheLogin(username, request.getParameter("pwd"));

            if(user == null){
                session.setAttribute("loginErrMsg","用户名或密码错误");
                session.setAttribute("loginUserName",username);
                response.sendRedirect("login.jsp");
            }else if("1".equals(user.getSysCode())){
                //有匹配数据就用户对象放在session中,
                session.setAttribute("user",user);
                //这是子账号
                response.sendRedirect("index.jsp");
            }else{
                //获取所有栏目
                List<NewsChnl> sumChnl = cu.getSumChnl();
                //有匹配数据就用户对象放在session中,
                session.setAttribute("user",user);
                //登录后从第一页查询
                session.setAttribute("pageIndex",1);
                //放入第一页数据
                session.setAttribute("list",uu.getPageUser(1,5));
                //放入最大页数
                session.setAttribute("sumPage",uu.getSumUserPage(5));
                //放入所有栏目
                session.setAttribute("chnlList",sumChnl);
                response.sendRedirect("index.jsp");
            }

        }else{
            session.setAttribute("loginCaptchaErrMsg","验证码错误");
            response.sendRedirect("login.jsp");
        }
    }
    private void doUserPage(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        try {
            this.updatePage(request,response,uu);
            response.sendRedirect("/page/AccountManagement.jsp");
        } catch (IOException e) {

        }
    }
    private void addUser(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        HttpSession session = request.getSession();
        try {
            boolean b = uu.addUser(request.getParameter("username"), request.getParameter("pwd"));
            String msg = b ? "新增用户成功" : "新增用户失败";
            session.setAttribute("addUserMSG",msg);
            session.removeAttribute("searchAcct"); // 操作后清除搜索标识
//            session.setAttribute("pageIndex",new Integer(1));//重新设置返回第一页
            //更新页数,更新对应的页数数据
            this.updatePage(request,response,uu);
            response.sendRedirect("/page/AccountManagement.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void delUser(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        HttpSession session = request.getSession();
        //获取要删除的账号,再根据 , 拆分;
        try {
            String msg= null;
            SysUser user = (SysUser) session.getAttribute("user");
            String delUserAcct = request.getParameter("delUserAcct");
            if(delUserAcct.contains(user.getAcct())){
                msg = "不能删除正在登录的本用户";
            }else{
                String[] split = delUserAcct.split(",");
                boolean b = uu.delUser(split);
                msg = b ? "删除用户成功" : "删除用户失败";
                this.updatePage(request,response,uu);
            }
            session.setAttribute("delUserMSG",msg);
            session.removeAttribute("searchAcct"); // 操作后清除搜索标识
//            session.setAttribute("pageIndex",new Integer(1));//重新设置返回第一页
            //更新页数,更新对应的页数数据
            response.sendRedirect("/page/AccountManagement.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void editUser(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        HttpSession session = request.getSession();
        SysUser user = (SysUser) session.getAttribute("user");
        //获取到 需要修改的账号
        String oldAcct = request.getParameter("oldAcct");
        //获取到 需要修改为的 新账号
        String editUserAcct = request.getParameter("editUserAcct");
        //获取到 密码
        String editUserPwd = request.getParameter("editUserPwd");
        try {
            boolean b = uu.editUser(oldAcct, editUserAcct, editUserPwd);
            String msg = b ? "修改用户成功" : "修改用户失败";
            if(oldAcct.equals(user.getAcct()) && msg.equals("修改用户成功")){
                session.invalidate();
                response.sendRedirect("login.jsp");
                return;
            }
            session.setAttribute("editUserMSG",msg);
            session.removeAttribute("searchAcct"); // 操作后清除搜索标识
//            session.setAttribute("pageIndex",new Integer(1));//重新设置返回第一页
            this.updatePage(request,response,uu);
            response.sendRedirect("/page/AccountManagement.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void doAccreditUser(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        String accUser = request.getParameter("accUser");
        String chnlName = request.getParameter("chnlName");
        HttpSession session = request.getSession();
        try {
            boolean b = uu.accUser(accUser, chnlName);
            String msg = b ? "用户授权修改成功" : "用户授权修改失败";
            session.setAttribute("accUserMSG",msg);
            session.removeAttribute("searchAcct"); // 操作后清除搜索标识
//            session.setAttribute("pageIndex",new Integer(1));//重新设置返回第一页
            this.updatePage(request,response,uu);
            response.sendRedirect("/page/AccountManagement.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void searchUser(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        HttpSession session = request.getSession();
        String selAcct = request.getParameter("selAcct");
        session.setAttribute("pageIndex",new Integer(1));
        try {
            if(selAcct.isEmpty()){
                session.removeAttribute("searchAcct");
            }else {
                session.setAttribute("searchAcct",selAcct); //设置一个识别是否是搜索分页的信息,把要搜索的账号放入session
            }
            this.updatePage(request,response,uu);
            response.sendRedirect("/page/AccountManagement.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doFindUser(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        try {
            String name = request.getParameter("name");
            String user = uu.findUser(name);
            String msg = user.isEmpty() ? "0" : "1";
            PrintWriter writer = response.getWriter();
            writer.println(msg);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void doExit(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        try {
            request.getSession().invalidate();
            response.sendRedirect("login.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //更新分页数据
    private void updatePage(HttpServletRequest request,HttpServletResponse response,UserUtil uu) throws ServletException{
        HttpSession session = request.getSession();
        try {
            String searchAcct = (String) session.getAttribute("searchAcct");
            //获取最大页数
            //判断是搜索分页还是普通分页,然后传回对应的最大页数
            int sumUserPage = searchAcct == null ? uu.getSumUserPage(5) : uu.getSelUserSumPgae(searchAcct,5);

            //由于增删改查都公用一个更新,增删改没有返回request的下标信息,所以要判断一下,如果从request中获取不到下标,就从session中获取
            String pageIndex = request.getParameter("pageIndex");
            int index = pageIndex == null ?   (Integer) session.getAttribute("pageIndex") : Integer.parseInt(pageIndex);
            //判断下标是否越界,小于0就强制为1,大于最大页数就强制为最大页数
            index = index > 0 ?  index <= sumUserPage ? index : sumUserPage   : 1;
            //根据下标,返回对应页数的数据
            List<UserMsg> pageUser = searchAcct == null ? uu.getPageUser(index, 5) : uu.selUser(searchAcct,index,5);
            //更新页面下标,对应页面数据,最大页数

            session.setAttribute("pageIndex",index);
            session.setAttribute("list",pageUser);
            session.setAttribute("sumPage",sumUserPage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
